package com.chezhujie.www.controller.admin;


import com.chezhujie.www.domain.Trole;
import com.chezhujie.www.domain.Trolepermission;
import com.chezhujie.www.service.TroleService;
import com.chezhujie.www.service.TrolepermissionService;
import com.chezhujie.www.service.TuserroleService;
import com.xy.core.page.Pagination;
import com.xy.core.utils.ConvertObj;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;




@Controller
@RequestMapping("role")
public class TroleController /*extends BaseController*/{
	private static final Logger log = LoggerFactory.getLogger(TroleController.class);
	public TroleController() {
	}
 
 
 	/**
	 * 角色新增页面
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("troleAdd.do")
	public String add(HttpServletRequest request, ModelMap model) {
		model.addAttribute("trole", new Trole());
		model.addAttribute("perms", new ArrayList<String>());
      setDict(model);
		return "role/troleEdit";
	}

	/**
	 * 角色保存
	 * 
	 * @param trole
	 * @param request
	 * @param model
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("troleSave.do")
	public String save(Trole trole, HttpServletRequest request, ModelMap model,String[] perms) throws Exception{
		if(trole.getRoleid()!=null && !"".equals(trole.getRoleid())){
			
			troleService.updateTrole(trole);
				//
				List<Trolepermission> rpset = trolepermissionService.findTpermissionByRoleid(trole.getRoleid());

				if (rpset != null) {
					
					@SuppressWarnings("rawtypes")
					List permidList=new ArrayList();
					for (Trolepermission t : rpset)
							permidList.add(t.getPermid());
						trolepermissionService.deleteTrolepermission(permidList);
				}
				Set<String> set = splitPerms(perms);
				for (String p : set) {
					Trolepermission tp = new Trolepermission();
					tp.setRoleid(trole.getRoleid());
					tp.setUri(p.trim());
					trolepermissionService.insertTrolepermission(tp);
				}
		}else{
			if (trole.getTusers() == null || trole.getTusers().size() == 0) {
				trole.setTusers(null);
			}
			if (trole.getTrolepermissions() == null
					|| trole.getTrolepermissions().size() == 0) {
				trole.setTrolepermissions(null);
			}

			troleService.insertTrole(trole);
			if (perms != null) {
				//
				Set<Trolepermission> rpset = trole.getTrolepermissions();
				if (rpset != null) {
					
					@SuppressWarnings("rawtypes")
					List permidList=new ArrayList();
					for (Trolepermission t : rpset)
							permidList.add(t.getPermid());
						trolepermissionService.deleteTrolepermission(permidList);
				}
				Set<String> set = splitPerms(perms);
				for (String p : set) {
					Trolepermission tp = new Trolepermission();
					tp.setRoleid(trole.getRoleid());
					tp.setUri(p);
					trolepermissionService.insertTrolepermission(tp);
				}
			}
		}
		
      
		return "redirect:troleList.do";
	}

	/**
	 * 角色删除
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping("troleDelete.do")
	public String delete(@RequestParam("ids") List<String> roleidList) throws Exception{
		try {
         if (roleidList != null) {
   			troleService.deleteTrole(roleidList);
   		}
         } catch (Exception e) {
   			log.error("trole delete error:", e); 
            throw e;
   		}
		return "redirect:troleList.do";
	}
	 
	/**
	 * 角色编辑页面
	 * 
	 * @param roleid
	 * @param request
	 * @param model
	 * @return
	 */
//	@RequestMapping("troleEdit.do")
	/*public String edit(String roleid, HttpServletRequest request, ModelMap model) throws Exception{
      try {
   		Map<String, Object> param = new HashMap<String, Object>();
   		param.put("roleid", roleid);
         Trole trole = troleService.getTrole(param);
   		model.addAttribute("trole", trole);
         model.addAttribute("actionEdit", request.getParameter("actionEdit"));
         setDict(model);
         } catch (Exception e) {
   			log.error("trole edit error:", e); 
            throw e;
   		}
		return "troleEdit";
	}*/
	@RequestMapping("troleEdit.do")
	public String edit(String roleid, HttpServletRequest request, ModelMap model) {
		Trole trole = troleService.get(roleid);
		model.addAttribute("trole", trole);
		@SuppressWarnings("unchecked")
		Set<Trolepermission> set = trole.getTrolepermissions();
		List<String> l = new ArrayList<String>();
		for (Trolepermission t : set) {
			l.add(t.getUri());
		}
		model.addAttribute("perms", l);
		setDict(model);
		return "role/troleEdit";
	}

	private Set<String> splitPerms(String[] perms) {
		Set<String> set = new HashSet<String>();
		if (perms != null) {
			for (String perm : perms) {
				for (String p : StringUtils.split(perm, ',')) {
					if (!StringUtils.isBlank(p)) {
						set.add(p);
					}
				}
			}
		}
		return set;
	}

	/**
	 * 角色详情
	 * 
	 * @param roleid
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("troleDetail.do")
	public String detail(String roleid, HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception{
      try {
      	
    		Trole trole = troleService.get(roleid);
    		model.addAttribute("trole", trole);
    		@SuppressWarnings("unchecked")
    		Set<Trolepermission> set = trole.getTrolepermissions();
    		List<String> l = new ArrayList<String>();
    		for (Trolepermission t : set) {
    			l.add(t.getUri());
    		}
    		model.addAttribute("perms", l);
    		setDict(model);
            } catch (Exception e) {
   			log.error("trole detail error:", e); 
            throw e;
   		  }
		return "role/troleView";
	}
	 
	/**
	 * 角色查询（分页）
	 * 
	 * @param trole
	 * @param pageNo
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("troleList.do")
	public String listPage(Trole trole, Integer pageNo, String order,
			String sort,HttpServletRequest request, ModelMap model) throws Exception{
      try {   
   		if (pageNo == null)
   			pageNo = 1;
         Pagination pagination = troleService.getTroleList(toMap(trole), 20, pageNo,
   				order, sort);          
         if(trole.getRolename()!=null && "".equals(trole.getRolename())){
        	 request.setAttribute("rolename", trole.getRolename());
         }
         if(trole.getIs_super()!=null && "".equals(trole.getIs_super())){
        	 request.setAttribute("getIs_super", trole.getIs_super());
         }
   		model.addAttribute("pagination", pagination);
         setDict(model);
         } catch (Exception e) {
			log.error("trole listPage error:", e); 
         throw e;
		   }
		return "role/troleList";
	}
	 
	/**
	 * 角色查询
	 * 
	 * @param trole
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("troleList1.do")
	public String list(Trole trole, HttpServletRequest request, ModelMap model) throws Exception{
      try {
   		Map<String,Object> map = troleService.getTroleList(toMap(trole));
   		model.addAttribute("list", map.get("rows"));
   		model.addAttribute("total", map.get("total"));
         setDict(model);
         } catch (Exception e) {
   			log.error("trole list error:", e); 
            throw e;
   		}
		return "role/troleList";
	}
	 

 	/***
	 * 将页面输入信息转成map
	 * 
	 * @param trole
	 * @return
	 */	private Map<String,Object> toMap(Trole trole){
		  
		return ConvertObj.toMap(trole);
	}
   
	/**
	 * 设置页面所需的数据字典
	 * @param model
	 */
	private void setDict(ModelMap model){
		
	}



   
      
	@Resource
	private TroleService troleService;
	
	@Resource
	private TrolepermissionService trolepermissionService;
	@Resource
	private TuserroleService tuserroleService;

}